package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.MissionItemAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.MenuE;
import com.infore.airsupervise.bean.MissionE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.MissionBiz;
import com.infore.airsupervise.biz.impl.MissionBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.MissionQueryDrawerFragment;
import com.infore.airsupervise.ui.widget.SwipeRecyclerView;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.rey.material.widget.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * @features: 移动执法任务列表展示界面（修改）
 * @author: WuTao
 * @date: 2017/4/7 09:28
 */
public class NewMissionListActivity extends BaseTitleBarActivity
        implements SwipeRecyclerView.OnActionListener, MissionQueryDrawerFragment.ConfigListener {

    @BindView(R.id.refreshRecyclerView)
    SwipeRecyclerView swipeRecyclerView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.fab_image)
    FloatingActionButton fabImage;
    @BindView(R.id.btn_search)
    AwesomeTextView btnSearch;

    private MissionQueryDrawerFragment queryDrawerFrag; //抽屉布局

    private MissionItemAdapter adapter;
    private List<MissionE> list = new ArrayList<>();//列表集合

    private MissionBiz missionBiz;

    private String userId;
    private int missionType; //任务标识
    private MenuE menuE;

    private String startTime;
    private String endTime;
    private int state;
    private int from ; //是否是从执法创建界面跳转的标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_mission);
        ButterKnife.bind(this);
        try {
            Intent it = getIntent();
            menuE = (MenuE) it.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            missionType = menuE.getmId();
            from = it.getIntExtra("from",0);
            //用户id
            userId = UserE.getUserInfo().getUserId();
            //网络请求业务
            missionBiz = new MissionBizImpl();
            //初始化UI
            initViews();
        } catch (Exception ex) {
            ToastUtil.showShort(ctx, "数据传递错误，请回退到上一级");
        }
    }


    private void initViews() {
        //顶部导航栏
        title.setText(menuE.getTitle());
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_FILTER);
        //抽屉布局
        queryDrawerFrag = new MissionQueryDrawerFragment(this);
        getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, queryDrawerFrag).commit();
        //浮动按钮
        if (missionType == StatusConst.MISSION_ZP) {
            fabImage.setVisibility(View.VISIBLE);
        }
        initRecycleView();
    }


    /**
     * 初始化当前任务列表
     **/
    private void initRecycleView() {
        adapter = new MissionItemAdapter(R.layout.item_current_mission, list);
        swipeRecyclerView.setAdapter(adapter);
        swipeRecyclerView.setActionListener(this);
        // 首次自动刷新
        swipeRecyclerView.getSwipeLayout().setRefreshing(true);
        swipeRecyclerView.onRefresh();
        if(missionType == StatusConst.MISSION_YB) {
            adapter.addHeaderView(getLayoutHeaderView());
            adapter.setHeaderAndEmpty(true);
        }
    }

    /**
     * 获取任务列表
     */
    private void getMissionList(final boolean isRefresh) {

        Call<BaseResponse> call = missionBiz.sendMissionListRequest(userId, missionType, ""
                , startTime, endTime, state,
                new OnServerResponseListener<List<MissionE>>() {
                    @Override
                    public void onSucceed(List<MissionE> result, String desc) {
                        swipeRecyclerView.commonSuccessHandle(isRefresh, result.size());
                        if (isRefresh) {
                            list.clear();
                        }
                        list.addAll(result);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                        swipeRecyclerView.commonFailedHandle(isRefresh, errorCode, title, desc);
                    }
                });
        requests.add(call);
    }

    /**
     * 头布局
     * @return
     */
    private View getLayoutHeaderView(){
        View view = getLayoutInflater().inflate(R.layout.item_mission_header,(ViewGroup)swipeRecyclerView.getRecyclerView().getParent(),false);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MenuE menuE = new MenuE(StatusConst.MISSION_DS_ME, R.drawable.ic_event_analysis,
                        "审核中的任务", "查看需要处理的任务，实时跟进", NewMissionListActivity.class);
                JumpUtil.jumpFromTo(ctx,NewMissionListActivity.class,Constants.INTENT_OBJ_KEY,menuE);
            }
        });
        return view;
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(from == 1){
            Intent it = new Intent();
            it.putExtra(Constants.INTENT_STR_KEY,list.get(position).getId());
            setResult(RESULT_OK,it);
            finish();
        }else {
            JumpUtil.jumpFromTo(this, NewMissionDetailActivity.class, Constants.INTENT_OBJ_KEY, list.get(position));
        }

    }

    @Override
    public void onRefresh() {
        getMissionList(true);
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRecyclerView.getAdapter().loadMoreEnd();
                swipeRecyclerView.getSwipeLayout().setEnabled(true);
            }
        }, 1000);
    }

    /**
     * 抽屉显示隐藏
     */
    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        if (!drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.openDrawer(Gravity.RIGHT);
        } else {
            drawerLayout.closeDrawers();
        }

    }

    @Override
    protected void onLeftMenuClick(View view) {
        if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawers();
        } else {
            super.onLeftMenuClick(view);
        }
    }


    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawers();
        } else {
            super.onBackPressed();
        }
    }

    @OnClick({R.id.btn_search, R.id.fab_image})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:  //搜索
                Bundle bundle = new Bundle();
                bundle.putInt( Constants.INTENT_INT_KEY, missionType );
                bundle.putInt("from" , from);
                JumpUtil.jumpFromTo(ctx, NewMissionQueryActivity.class,bundle);
                break;
            case R.id.fab_image://浮动按钮
                //发起一个新任务
                ToastUtil.showShort(this, "发起一个新任务");
                JumpUtil.jumpFromTo(this, NewMissionCreateActivity.class);
                break;
        }
    }

    @Override
    public void onConfigListener(String startTime, String endTime, int state) {
        if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawers();
            this.startTime = startTime;
            this.endTime = endTime;
            this.state = state;
            swipeRecyclerView.getSwipeLayout().setRefreshing(true);
            swipeRecyclerView.onRefresh();
        }

    }

    /**
     * 点击事件
     */

}
